package com.dc.qqlogin.service;

import com.dc.web.base.BaseWebController;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: KEYD
 * @Date: 2020/2/14 20:48
 * @Desc: QQ授权
 */
@Controller
@RequestMapping("/login")
public class QQAuthorithController extends BaseWebController {

    //1、生成授权链接
    @RequestMapping("/qqAuth")
    public String qqAuth(HttpServletRequest request) {
        try {
            String authorizeURL = new Oauth().getAuthorizeURL(request);
            System.out.println("dcauthorizeURL:" + authorizeURL);
            //return "index";
            return "redirect:" + authorizeURL; //回调地址的问题。跳不进去
        } catch (QQConnectException e) {
            return ERROR_500_FTL;
        }
    }

    //2、QQ授权回调
    @RequestMapping("/qqlogin")
    public String loginBack(HttpServletRequest request) {
        System.out.println("code:");
        //1、获取到授权码 code
        try {
            AccessToken accessTokenByRequest = (new Oauth()).getAccessTokenByRequest(request);
            System.out.println("DDccccc:" + accessTokenByRequest.toString());
            if (accessTokenByRequest == null) {
                return ERROR_500_FTL;
            }
            String accessToken = accessTokenByRequest.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                return ERROR_500_FTL;
            }
            //使用accessToken获取用户openId
            OpenID openIDObj = new OpenID(accessToken);
            String openId = openIDObj.getUserOpenID();
            if (StringUtils.isEmpty(openId)) {
                return ERROR_500_FTL;
            }
            /** 使用 openId 查询数据库是否已经管理账号信息 **/
            //获取用户信息
            UserInfo userInfo = new UserInfo(accessToken, openId);
            UserInfoBean userInfoBean = userInfo.getUserInfo();
            if (userInfo == null) {
                return ERROR_500_FTL;
            }
            String avatarURL100 = userInfoBean.getAvatar().getAvatarURL100();  //QQ用户头像
        } catch (QQConnectException e) {
            return ERROR_500_FTL;
        }
        //2、根据授权码获取 accessToken
        //3、根据accessToken获取用户openId
        return "index";
    }

}
